<?php
//$Id: app.php 272 2012-04-16 06:04:33Z tomqin@gmail.com $

/**
 * App ARESCMS框架入口文件
 *
 * @copyright       Copyright (C) 2010-2012 ARESCMS Inc.
 * @author          TomQin <tomqin@gmail.com>
 * @license         http://www.arescms.cn/license/
 * @package Core
 */

//框架标记
define('DS', DIRECTORY_SEPARATOR);
define('IN_ARESCMS', true);
define('ARESCMS_ROOT', substr(__FILE__, 0, -14));
define('SYSTEM_PATH', ARESCMS_ROOT.'system'.DS);
define('DATA_PATH', ARESCMS_ROOT.'data'.DS);

//主机协议
define('SITE_PROTOCOL', isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://');

//当前访问的主机名
define('SITE_URL', (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : ''));

//来源
define('HTTP_REFERER', isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '');

//系统开始时间
define('SYS_START_TIME', microtime(true));
define('TIMESTAMP', $_SERVER['REQUEST_TIME']);

//设置错误信息
error_reporting(E_ALL ^ E_NOTICE);
error_reporting(E_ALL);
//set_error_handler('my_error_handler');

/*
//设置本地时差
date_default_timezone_set(Config::get('system.timezone'));

//系统字符集
define('CHARSET', Config::get('system.charset'));

//系统路径
define('STATIC_URL',  Config::get('system.static_url'));
define('UPLOAD_URL',  Config::get('system.upload_url'));
define('UPLOAD_PATH', Config::get('system.upload_path'));

//IP地址
define('IP_ADDRESS', ip_address());

//输出页面字符集
header('Content-type: text/html; charset='.CHARSET);

//GZIP 输出模式
if (Config::get('system.gzip') && function_exists('ob_gzhandler')) {
    ob_start('ob_gzhandler');
} else {
    ob_start();
}
*/

spl_autoload_register(array('App', 'autoLoad'));

// $Id: app.php 272 2012-04-16 06:04:33Z tomqin@gmail.com $

/**
 * App 应用程序框架基本操作类
 *
 * @copyright       Copyright (C) 2010-2012 ARESCMS Inc.
 * @author          TomQin <tomqin@gmail.com>
 * @license         http://www.arescms.cn/license/
 * @package Core
 */

class App
{
    /**
     * Cookie 设置
     */
    public static function getCookie($name, $default = null){
        return (isset($_COOKIE[$name]) && $_COOKIE[$name]) ? $_COOKIE[$name] : $default;
    }

    public static function setCookie($name, $value, $minutes = 0, $path = '/', $domain = null, $secure = false, $http_only = false){
        if (headers_sent()) return false;

        $time = ($minutes !== 0) ? TIMESTAMP + ($minutes * 60) : 0;
        if ($minutes < 0){
            unset($_COOKIE[$name]);
        }else{
            $_COOKIE[$name] = $value;
        }

        return setcookie($name, $value, $time, $path, $domain, $secure, $http_only);
    }

    /**
     * 配置信息
     */
    private static $configs = array();

    public static function getConfig($name, $default){
        if(empty(self::$configs)) {
            self::initConfig();
        }
        return isset(self::$configs[$key]) ? self::$configs[$key] : $default;
    }

    public static function initConfig(){
        $cityid = self::getCityId();
        self::$configs = require DATA_PATH . $cityid . DS . 'config.inc.php';
    }

    /**
     * 获取客户端 IP 地址
     */
    public static function getClientIp(){
        $ip = $_SERVER['REMOTE_ADDR'];
        if (isset($_SERVER['HTTP_CLIENT_IP']) && preg_match('/^(\d{1,3}\.){3}\d{1,3}$/', $_SERVER['HTTP_CLIENT_IP'])) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif(isset($_SERVER['HTTP_X_FORWARDED_FOR']) && preg_match_all('/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/s', $_SERVER['HTTP_X_FORWARDED_FOR'], $matches)) {
            foreach ($matches[0] AS $xip) {
                if (!preg_match('#^(10|172\.16|192\.168)\.#', $xip)) {
                    $ip = $xip;
                    break;
                }
            }
        }
        return $ip;
    }

    /**
     * 载入文件
     *
     * App::action('front/Setting_Db')    Setting_Db_Action   action/front/setting_db.php
     * App::action('admin/sub/Class')     Class_Action        action/admin/sub/class.php
     * App::action('Test')                Test_Action         action/test.php
     * App::moudle('Setting_Db')          Setting_Db_Moudle   moudle/setting_db.php
     * App::moudle('Sub/Class')           Class_Moudle        moudle/sub/class.php
     * App::moudle('Test')                Test_Moudle         moudle/test.php
     *
     */

    public static function import($file) {
        if(is_file($file)) {
            include_once $file;
        } else {
            throw new Exception('Oops! System file lost: '.$file);
        }
        return true;
    }

    private static $objects = array();

    public static function moudle($name, $path = ''){
        return self::load_class('moudle', ($path ? $path.'/'.$name : $name), true);
    }

    public static function action($name, $path = ''){
        return self::load_class('action', ($path ? $path.'/'.$name : $name), true);
    }

    //仅限于 class
    public static function autoLoad($name){
        self::import(SYSTEM_PATH . 'class' .DS. str_replace('_', DS, strtolower($name)) . '.php');
    }

    private static function load_class($type, $name, $auto = false, $init = array()){
        if(in_array($type, array('moudle', 'action'))){
            $class = basename($name) . "_{$type}";
            $file  = SYSTEM_PATH. $type .DS. str_replace('/', DS, strtolower($name)) . '.php';
        }else{
            throw new Exception('Oops! Wrong class type: '.$type);
        }
        if(!class_exists($class, false)){
            self::import($file);
        }

        //if(isset(self::$objects[$class]))
        //    return self::$objects[$class];

        if($auto){
            /**
             * see http://www.phpeye.com/feedentry/viewen/id/9238
             */
            switch(count($init)) {
                case 0:
                  $object = new $class();break;
                case 1:
                  $object = new $class($init[0]);break;
                case 2:
                  $object = new $class($init[0],$init[1]);break;
                case 3:
                  $object = new $class($init[0],$init[1],$init[2]);break;
                case 4:
                  $object = new $class($init[0],$init[1],$init[2],$init[3]);break;
                default:
                  throw new Exception('Oops! Too many args, less than 4 args!');
             }
             //self::$objects[$class] = $object;
             return $object;
        }else{
            return true;
        }
    }

}
?>